package com.xxxx.seckill.controller;

import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.pojo.dto.GoodsDto;
import com.xxxx.seckill.service.IGoodsService;
import com.xxxx.seckill.vo.DetailVo;
import com.xxxx.seckill.vo.RespBean;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpCookie;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService iGoodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * QPS : 300
     * 缓存后 QPS: 600
     * 商品页面
     *
     * @param user
     * @param model
     * @return
     */
    @GetMapping("/toList")
    @ResponseBody
    public String toList(User user, Model model,
                         HttpServletRequest request, HttpServletResponse response) {
        log.info("user:{}。。。。。。", user);

//        if (user == null) {
//            return "login";
//        }

        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        List<GoodsDto> goodsAll = iGoodsService.getGoodsDto();

        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsAll);
//        log.info("页面跳转成功");
        //创建 WebContext
        WebContext context = new WebContext(request, response,
                request.getServletContext(),
                request.getLocale(), model.asMap());
        // 渲染
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);
        if (!StringUtils.isEmpty(html)) {
            //设置缓存，1分钟
            valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }
        return html;
    }

    /**
     * 商品详情
     *
     * @param model
     * @param user
     * @param id
     * @return
     */
    @GetMapping("/detail2/{goodsId}")
    @ResponseBody
    public String detail(Model model, User user, @PathVariable("goodsId") int id,
                         HttpServletRequest request, HttpServletResponse response) {
        if (user == null) {
            return "login";
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail:" + id);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        //秒杀状态
        int secKillStatus = 0;
        //剩余开始时间
        int remainSeconds = 0;
        //获取对应的时间 0：未开始 1：开始中 2：已结束
        GoodsDto goodsDto = iGoodsService.getDetail(id);
        Date startDate = goodsDto.getStartDate();
        Date endDate = goodsDto.getEndDate();
        Date nowData = new Date();
        if (nowData.before(startDate)) {
            secKillStatus = 0;
            remainSeconds = (int) ((startDate.getTime() - nowData.getTime()) / 1000);
        } else if (nowData.after(endDate)) {
            secKillStatus = 2;
            secKillStatus = -1;
        } else {
            secKillStatus = 1;
        }
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("user", user);
        model.addAttribute("goods", goodsDto);

        WebContext context = new WebContext(request, response,
                request.getServletContext(),
                request.getLocale(),
                model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", context);
        if (!StringUtils.isEmpty(html)) {
            valueOperations.set("goodsDetail:" + id, html, 60, TimeUnit.SECONDS);
        }
        return html;
    }


    /**
     * 商品详情 ，静态页面 ，前后端分离
     *
     * @param user
     * @param id
     * @return
     */
    @GetMapping("/detail/{goodsId}")
    @ResponseBody
    public RespBean detail2(User user, @PathVariable("goodsId") int id) {
        //秒杀状态
        int secKillStatus = 0;
        //剩余开始时间
        int remainSeconds = -1;
        //获取对应的时间 0：未开始 1：开始中 2：已结束
        GoodsDto goodsDto = iGoodsService.getDetail(id);
        Date startDate = goodsDto.getStartDate();
        Date endDate = goodsDto.getEndDate();
        Date nowData = new Date();
        if (nowData.before(startDate)) { //未开始
            secKillStatus = 0;
            remainSeconds = (int) ((startDate.getTime() - nowData.getTime()) / 1000);
        } else if (nowData.after(endDate)) { //已结束
            secKillStatus = 2;

        } else { //进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        DetailVo detailVo = new DetailVo(user, goodsDto, secKillStatus, remainSeconds);
        return RespBean.success(detailVo);
    }
}
